﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Pay.DTO;
using Pay.IService;
using Pay.Core;
using System.Text.RegularExpressions;
using Pay.TO;
using Flurl.Http;

namespace Pay.Service {
	public class kltPayService : ServiceBase2, IPayService, IDisposable {
		private ISettingService _iSettingService;
		private IMerchantService _iMerchantService;
		private IChargeService _iChargeService;
		private IPayHtmlService _iPayHtmlService;
		private IOrderService _iOrderService;
		private IPayNotifyService _iPayNotifyService;
		private kltPaySign _kltPaySign;
		public kltPayService(IUnitOfWork iUnitOfWork, ISettingService iSettingService,
							IMerchantService iMerchantService, IChargeService iChargeService,
		                     IPayHtmlService iPayHtmlService,IOrderService iOrderService,
		                     IPayNotifyService iPayNotifyService)
			: base(iUnitOfWork) {
			_iSettingService = iSettingService;
			_iMerchantService = iMerchantService;
			_iChargeService = iChargeService;
			_iPayHtmlService = iPayHtmlService;
			_iOrderService = iOrderService;
			_iPayNotifyService = iPayNotifyService;
			_kltPaySign = new kltPaySign();
		}

		public Task<transfer_result> AgencyFund(apply_receive model) {
			throw new NotImplementedException();
		}

		public Task<certify_verify_result> CertifyVerify(certify_verify model) {
			throw new NotImplementedException();
		}

		public int DealItp(long id) {
			throw new NotImplementedException();
		}
		/// <summary>
		/// 开联通网关支付
		/// </summary>
		/// <returns>The pay.</returns>
		/// <param name="model">Model.</param>
		public Task<gateway_pay_result> GatewayPay(gateway_pay_model model) {
			throw new NotImplementedException();
		}

		public List<type_setting> GatewayPayBank() {
			throw new NotImplementedException();
		}

		public async Task<pay_notity> GatewayPayQuery(refund_model_query model) {
			var pay_html = _iPayHtmlService.Get(model.merchant_no, model.order_no);
			if (pay_html != null) {
				var query = new klt_gateway_query {
					version = "v1.5",
					signType = "1",
					merchantId = RequestMethod.KLT_PAY_PARTNER,
					orderNo = model.order_no,
					orderDatetime = pay_html.create_time.ToString("yyyyMMddHHmmss"),
					queryDatetime = DateTime.Now.ToString("yyyyMMddHHmmss")
				};
				var kltResult = await _kltPaySign.PayGateway<klt_gateway_notify>(query, "/mchtoq/orderquery");
				if (kltResult != null) {
					var srcMsg = _kltPaySign.SrcMsg(kltResult);
					if (_kltPaySign.VerifySign(srcMsg, System.Web.HttpUtility.UrlDecode(kltResult.signMsg), RequestMethod.KLT_PAY_SECRET_URL, false)) {
						if (kltResult.payResult.Equals("1")) {
							DateTime pay_time = kltResult.payDatetime.ToDateTime();
							string transaction_no = kltResult.mchtOrderId;
							int result = _iOrderService.PaySuceess(pay_html, transaction_no, pay_time);
							var charge = pay_html.charge.ToObject<charge_dto>();
							var notifyResult = await Notify(charge.merchant_no, charge.order_no);
							if (notifyResult != "OK") {
								//创建通知消息对象
								_iPayNotifyService.Save(new pay_notify_dto {
									merchant_no = charge.merchant_no,
									order_no = charge.order_no,
									pay_channel = charge.pay_info.pay_channel,
									type = 1,
									status = 2,
									create_time = DateTime.Now
								});
							}
							_iPayHtmlService.Remove(pay_html.id);
							return ApiResultToJson.Json("支付成功", new pay_notity { 
								order_no = kltResult.orderNo,
								tran_amount = kltResult.orderAmount,
								transaction_no = kltResult.mchtOrderId,
								pay_time = kltResult.payDatetime.ToDateTime()
							});
						}
					}
				}
			}

			return ApiResultToJson.Json<pay_notity>("网关支付查询异常");
		}

		public Task<refund_result> GatewayPayRefund(refund_model model) {
			throw new NotImplementedException();
		}

		public Task<refund_result> GatewayRefundQuery(refund_model_query model) {
			throw new NotImplementedException();
		}

		public Task<ApiResultMessage> InsteadReceive(verify_model_sms model) {
			throw new NotImplementedException();
		}

		public Task<ApiResultMessage> InsteadReceive(verify_model model) {
			throw new NotImplementedException();
		}

		public Task<int> ItpToFile(DateTime create_date) {
			throw new NotImplementedException();
		}
		/// <summary>
		/// 开联通网关支付
		/// </summary>
		/// <returns>The pay.</returns>
		/// <param name="model">Model.</param>
		public async Task<mall_result> MallPay(mall_model model) {
			var id = Guid.NewGuid().ToString("N");
			var notifyUrl = string.Format("{0}/klt_notify", _iSettingService.Get().site.api_url);
			var shipping = new shipping_dto();
			if (model.shipping != null) {
				shipping.ship_to = model.shipping.ship_to;
				shipping.region_id = model.shipping.area_id.HasValue ? model.shipping.area_id.Value : model.shipping.city_id;
				shipping.phone = model.shipping.phone; shipping.address = model.shipping.address;
				shipping.region_name = model.shipping.region_name;
				shipping.id_card = model.shipping.id_card;
				shipping.real_name = model.shipping.real_name;
				shipping.card_negative = model.shipping.card_negative;
				shipping.card_positive = model.shipping.card_positive;
			}
			model.orders.ForEach(c => { c.shipping_type = model.shipping_type; c.shipping = shipping; });
			//下单时间
			string orderDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
			var charge = _iChargeService.AddByMallPay(model);
			var htmls = new List<pay_html_dto>();
			var order_html = new pay_html_dto {
				id = id,
				html = model.orders.ToJson(),
				merchant_no = model.merchant_no,
				order_no = model.order_no,
				charge = charge.ToJson(),
				create_time = orderDateTime.ToDateTime()
			};
			htmls.Add(order_html);

			var klt_gateway_req = new klt_gateway_pay {
				inputCharset = "1",
				pickupUrl = string.Format("{0}/pay/sxy_notify", _iSettingService.Get().site.api_url),
				receiveUrl = notifyUrl,
				signType = "1",
				orderNo = model.order_no,
				orderAmount = model.tran_amount,
				orderCurrency = "156",
				orderDatetime = orderDateTime,
				productName = model.body,
				payType = "0",
				ext1 = id,
				merchantId = RequestMethod.KLT_PAY_PARTNER
			};
			klt_gateway_req.signMsg = _kltPaySign._sign(klt_gateway_req);
			var req_id = Guid.NewGuid().ToString("N");
			var request_url = string.Format("{0}/pay/klt_front/{1}", _iSettingService.Get().site.api_url, req_id);
			var pay_html = new pay_html_dto {
				id = req_id,
				html = klt_gateway_req.ToJson(),
				merchant_no = model.merchant_no,
				order_no = model.merchant_no,
				charge = RequestMethod.KLT_PAY_API_URL,
				create_time = orderDateTime.ToDateTime()
			};
			htmls.Add(pay_html);
			var ok = _iPayHtmlService.Save(htmls);
			if (ok) {
				var data = new mall_result { order_no = model.order_no, code_url = request_url };
				return ApiResultToJson.Json(data);
			}
			return await ApiResultToJson.JsonAsync<mall_result>("sql-data:html数据保存失败");
		}

		public Task<merchant_register_result> MerchantModify(long bind_id, string settle_type,PayChannel channel = PayChannel.None) {
			throw new NotImplementedException();
		}

		public Task<merchant_register_result> MerchantRegister(long bind_id, string settle_type,PayChannel channel = PayChannel.None) {
			throw new NotImplementedException();
		}

		public Task<merchant_register_result> MerchantRegister(merchant_register_model dto, string opt) {
			throw new NotImplementedException();
		}

		public Task<native_result> NativePay(native_model obj) {
			throw new NotImplementedException();
		}

		public async Task<string> Notify(string merchant_no, string order_no) {
			string result = string.Empty;
			charge_dto order = _iChargeService.Get(merchant_no, order_no);
			try {
				var data = new pay_notity {
					tran_amount = ((int)(order.order_amount * 100)).ToString(),
					order_no = order.order_no,
					transaction_no = order.pay_info.transaction_no,
					pay_time = order.pay_info.pay_time.HasValue ? order.pay_info.pay_time.Value : order.order_time,
					status = (order.status == ChargeStatus.Finish ? 1 : 2)
				};
				//失败的要再查询通道判断是否真失败,处理掉单
				//if (order.status != ChargeStatus.Finish) {
				//	var pay_model = new hx_head_base();
				//	pay_model.client_trans_id = order.order_no;
				//	pay_model.trans_timestamp = DateTime.Now.ToUnix();
				//	pay_model.data = data.ToJson();
				//	pay_model.sign = _rpaySign.Sign(pay_model);
				//	var resultApi = await _rpaySign.PayGateway<hx_query_result>(pay_model);
				//	if (resultApi != null) {
				//		if (resultApi.resp_code == "000000" && resultApi.data.resp_code == "PAY_SUCCESS" /*&& resultApi.data.withdrawals_status == "WITHDRAWALS_SUCCESS"*/) {
				//			data.status = 1;
				//			var pay_time = DateTime.Now;
				//			_iChargeService.FailOrUnConfirmToSuceess(merchant_no, order.order_no, pay_time);
				//		}
				//	}
				//}
				data.result_msg = (data.status == 1 ? "支付成功" : order.fail);
				if (string.IsNullOrEmpty(order.notify)) return "OK";
				var notify_result = await order.notify.PostJsonAsync(ApiResultToJson.Json(data)).ReceiveJson<ResultMessage<string>>();
				result = notify_result.data;
				var log = IocHelper.Get<ILogHelper>("info");
				log.Info(order.order_no + ":" + notify_result.ToJson());
			} catch (Exception ex) {
				var log = IocHelper.Get<ILogHelper>("info");
				log.Error("订单通道查询异常:" + order.order_no);
				string message = string.Format("消息类型：{0}\r\n消息内容：{1}\r\n引发异常的方法：{2}\r\n引发异常源：{3}"
								, ex.GetType().Name, ex.Message, ex.TargetSite, ex.Source + ex.StackTrace);
				log.Error(message);
			}
			return result;
		}

		public Task<string> NotifyTransfer(string merchant_no, string order_no) {
			throw new NotImplementedException();
		}

		public Task<quick_pay_result> QuickPay(quick_sms_model model) {
			throw new NotImplementedException();
		}

		public Task<quick_pay_result> QuickPay(quick_pay_model model) {
			throw new NotImplementedException();
		}

		public Task<pay_notity> QuickPayQuery(refund_model_query model) {
			throw new NotImplementedException();
		}

		public Task<refund_result> QuickPayRefund(refund_model model) {
			throw new NotImplementedException();
		}

		public Task<refund_result> QuickPayRefundQuery(refund_model_query model) {
			throw new NotImplementedException();
		}

		public Task<ApiResultMessage> QuickPaySendsms(quick_sendsms_model model) {
			throw new NotImplementedException();
		}

		public Task<quota_result> Quota(string merchant_no, string busiType) {
			throw new NotImplementedException();
		}

		public Task<transfer_result> ReTransfer(long id) {
			throw new NotImplementedException();
		}

        public Task<transfer_result> TokenTransfer(long id) {
            throw new NotImplementedException();
        }

        public Task<transfer_result> TokenTransferQuery(transfer_query model) {
            throw new NotImplementedException();
        }

        public Task<batch_transfer_result> Transfer(batch_transfer model) {
			throw new NotImplementedException();
		}

		public Task<transfer_result> Transfer(apply_transfer model) {
			throw new NotImplementedException();
		}

		public Task<int> TransferBack(long batchId, string noticeTranId, long merchant_id) {
			throw new NotImplementedException();
		}

		public Task<int> TransferNotify(long batchId, string batchFileName, long merchant_id) {
			throw new NotImplementedException();
		}

		public Task<transfer_result> TransferQuery(transfer_query model) {
			throw new NotImplementedException();
		}
	}
}
